#include "parking_surveillance.h"
#include "ui_parking_surveillance.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QFileDialog>
#include <QDir>
#include <QTimer>

Parking_Surveillance::Parking_Surveillance(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Parking_Surveillance),
    isConnected(false),
    overlayLabel(nullptr)
{
    ui->setupUi(this);

    // 创建覆盖层
    createOverlay();
    // 初始化网络管理器
    networkManager = new QNetworkAccessManager(this);
    imageBuffer = new QBuffer(this);
    isStreaming = false;
    streamReply = 0;

    // 设置服务器URL
    serverUrl = "http://192.168.0.84:8080/?action=stream";

    // 初始化超时计时器
    timeoutTimer = new QTimer(this);
    timeoutTimer->setSingleShot(true);
    connect(timeoutTimer, SIGNAL(timeout()), this, SLOT(onTimeout()));

    // 新增：帧率控制计时器 - 限制显示频率
    frameTimer = new QTimer(this);
    frameTimer->setInterval(100); // 10帧/秒，避免卡顿
    connect(frameTimer, SIGNAL(timeout()), this, SLOT(processFrameBuffer()));

    // 新增：截图保存路径
    screenshotPath = "C:/Users/ZDH/Desktop/1/03-suicide-squad/ZDH/QT/tupian";

    // 确保截图目录存在
    QDir dir(screenshotPath);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
}

Parking_Surveillance::~Parking_Surveillance()
{
    destroyOverlay();
    delete ui;
}

void Parking_Surveillance::createOverlay()
{
    if (overlayLabel) {
        destroyOverlay();
    }

    qDebug() << "[Parking_Surveillance]: 创建覆盖层";

    overlayLabel = new QLabel(this);
    overlayLabel->setGeometry(0, 0, this->width(), this->height());
    // 统一覆盖层样式
    overlayLabel->setStyleSheet("background-color: rgba(128, 128, 128, 150); color: red; font-size: 70px; font-weight: bold;");
    overlayLabel->setAlignment(Qt::AlignCenter);
    overlayLabel->setText("设备未连接");
    overlayLabel->setVisible(true);
    overlayLabel->raise();
}

void Parking_Surveillance::destroyOverlay()
{
    qDebug() << "[Parking_Surveillance]: 销毁覆盖层";

    if (overlayLabel) {
        overlayLabel->setVisible(false);
        overlayLabel->deleteLater();
        overlayLabel = nullptr;
    }
}

void Parking_Surveillance::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);

    if (overlayLabel) {
        overlayLabel->setGeometry(0, 0, this->width(), this->height());
        overlayLabel->raise();
    }
}

void Parking_Surveillance::dataUpSlot(const QByteArray &msg)
{
    // 收到消息表示已连接
    if (!isConnected) {
        isConnected = true;
        destroyOverlay();
        qDebug() << "[Parking_Surveillance]: 首次收到MQTT消息，连接状态已更新";
    }

    qDebug() << "[Parking_Surveillance]: Received MQTT message";

    QJsonDocument doc = QJsonDocument::fromJson(msg);
    if(!doc.isObject())
    {
        qDebug() << "[Parking_Surveillance]: Invalid JSON format";
        return;
    }

    QJsonObject obj = doc.object();

    if(obj.contains("parking_status"))
    {
        int status = obj["parking_status"].toInt();
        qDebug() << "[Parking_Surveillance]: 停车状态:" << status;
    }

    if(obj.contains("camera_status"))
    {
        int status = obj["camera_status"].toInt();
        qDebug() << "[Parking_Surveillance]: 摄像头状态:" << status;
    }

    if(obj.contains("detection_status"))
    {
        int status = obj["detection_status"].toInt();
        qDebug() << "[Parking_Surveillance]: 检测状态:" << status;
    }
}

void Parking_Surveillance::setConnectedState(bool connected)
{
    isConnected = connected;
    qDebug() << "[Parking_Surveillance]: 连接状态设置为:" << connected;

    if (connected) {
        destroyOverlay();
    } else {
        if (!overlayLabel) {
            createOverlay();
        }
    }
}

void Parking_Surveillance::on_pushButton_clicked()
{
    if(isStreaming) {
        return;
    }

    // 清空帧缓冲区
    frameData.clear();

    // 创建HTTP请求
    QNetworkRequest request;
    request.setUrl(QUrl(serverUrl));
    request.setRawHeader("User-Agent", "MJPG-Streamer-Client");

    // 发送请求
    streamReply = networkManager->get(request);

    // 连接信号槽
    connect(streamReply, SIGNAL(readyRead()), this, SLOT(onStreamReadyRead()));
    connect(streamReply, SIGNAL(finished()), this, SLOT(onStreamFinished()));
    connect(streamReply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(onStreamError(QNetworkReply::NetworkError)));

    isStreaming = true;
    ui->label->setText("正在连接视频流...");
    qDebug() << "开始连接HTTP视频流:" << serverUrl;

    // 启动超时计时器（10秒）
    timeoutTimer->start(10000);

    // 启动帧处理计时器
    frameTimer->start();
}

void Parking_Surveillance::on_pushButton_2_clicked()
{
    if(!isStreaming) {
        // 修改弹窗大小为600x500
        QMessageBox msgBox;
        msgBox.setWindowTitle("提示");
        msgBox.setText("请先开始视频流");
        msgBox.setFixedSize(600, 500); // 设置弹窗大小
        msgBox.exec();
        return;
    }

    // 检查当前是否有图像显示
    if(!ui->label->pixmap() || ui->label->pixmap()->isNull()) {
        QMessageBox msgBox;
        msgBox.setWindowTitle("截图");
        msgBox.setText("没有可用的图像");
        msgBox.setFixedSize(600, 500);
        msgBox.exec();
        return;
    }

    // 第一步：弹出确认保存的对话框
    QMessageBox confirmBox;
    confirmBox.setWindowTitle("截图确认");
    confirmBox.setText("是否保存截图?");
    confirmBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);
    confirmBox.setDefaultButton(QMessageBox::Save);
    confirmBox.setFixedSize(600, 500);

    int reply = confirmBox.exec();

    // 如果用户选择取消，直接返回
    if(reply != QMessageBox::Save) {
        return;
    }

    // 第二步：自动保存到指定路径
    QPixmap pixmap = *ui->label->pixmap();

    // 生成默认文件名
    QString defaultFileName = QString("screenshot_%1.jpg")
            .arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));

    QString fileName = screenshotPath + "/" + defaultFileName;

    // 保存图像
    if(pixmap.save(fileName, "JPEG")) {
        QMessageBox msgBox;
        msgBox.setWindowTitle("截图成功");
        msgBox.setText(QString("截图已保存为:\n%1").arg(fileName));
        msgBox.setFixedSize(600, 500);
        msgBox.exec();
        qDebug() << "截图保存成功:" << fileName;
    } else {
        QMessageBox msgBox;
        msgBox.setWindowTitle("截图失败");
        msgBox.setText(QString("截图保存失败:\n%1").arg(fileName));
        msgBox.setFixedSize(600, 500);
        msgBox.exec();
        qDebug() << "截图保存失败:" << fileName;
    }
}

void Parking_Surveillance::on_pushButton_3_clicked()
{
    if(!isStreaming) {
        return;
    }

    if(streamReply) {
        streamReply->abort();
        streamReply->deleteLater();
        streamReply = 0;
    }

    isStreaming = false;
    timeoutTimer->stop();
    frameTimer->stop(); // 停止帧处理计时器
    ui->label->setText("视频流已停止");
    qDebug() << "已停止视频流";
}

void Parking_Surveillance::onStreamReadyRead()
{
    if(!streamReply || !isStreaming) {
        return;
    }

    // 停止超时计时器
    timeoutTimer->stop();

    // 读取所有可用数据并追加到缓冲区
    QByteArray data = streamReply->readAll();
    frameData.append(data);

    // 限制缓冲区大小，防止内存溢出
    if(frameData.size() > 10 * 1024 * 1024) { // 10MB限制
        frameData = frameData.right(5 * 1024 * 1024); // 保留最近5MB数据
        qDebug() << "缓冲区过大，已截断";
    }
}

// 新增：处理帧缓冲区的函数，由计时器定期调用
void Parking_Surveillance::processFrameBuffer()
{
    if (frameData.isEmpty() || !isStreaming) {
        return;
    }

    // 查找完整的JPEG帧 (以0xFFD8开始，以0xFFD9结束)
    int startPos = frameData.indexOf("\xFF\xD8");
    int endPos = frameData.indexOf("\xFF\xD9");

    if(startPos != -1 && endPos != -1 && endPos > startPos) {
        // 提取完整的JPEG帧
        QByteArray jpegData = frameData.mid(startPos, endPos - startPos + 2);

        // 创建QImage并显示
        QImage image;
        if(image.loadFromData(jpegData, "JPEG")) {
            QPixmap pixmap = QPixmap::fromImage(image);
            ui->label->setPixmap(pixmap.scaled(ui->label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
        }

        // 移除已处理的数据
        frameData = frameData.mid(endPos + 2);
    }
}

void Parking_Surveillance::onStreamFinished()
{
    qDebug() << "流连接结束";
    timeoutTimer->stop();
    frameTimer->stop();

    if(isStreaming) {
        ui->label->setText("流连接意外中断");
        isStreaming = false;
    }

    if(streamReply) {
        streamReply->deleteLater();
        streamReply = 0;
    }
}

void Parking_Surveillance::onStreamError(QNetworkReply::NetworkError code)
{
    qDebug() << "网络错误:" << code;
    timeoutTimer->stop();
    frameTimer->stop();

    QString errorMsg;
    switch(code) {
    case QNetworkReply::ConnectionRefusedError:
        errorMsg = "连接被拒绝";
        break;
    case QNetworkReply::RemoteHostClosedError:
        errorMsg = "远程主机关闭连接";
        break;
    case QNetworkReply::HostNotFoundError:
        errorMsg = "主机未找到";
        break;
    case QNetworkReply::TimeoutError:
        errorMsg = "连接超时";
        break;
    default:
        errorMsg = QString("网络错误: %1").arg(code);
        break;
    }

    ui->label->setText(errorMsg);
    isStreaming = false;

    if(streamReply) {
        streamReply->deleteLater();
        streamReply = 0;
    }
}

void Parking_Surveillance::onTimeout()
{
    if(isStreaming) {
        qDebug() << "连接超时";
        ui->label->setText("连接超时，请检查服务器状态");
        isStreaming = false;
        frameTimer->stop();

        if(streamReply) {
            streamReply->abort();
            streamReply->deleteLater();
            streamReply = 0;
        }
    }
}
